package com.work.game.ad.kaku;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.util.Log;
import android.widget.Toast;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.ATShowConfig;
import com.anythink.core.api.AdError;
import com.anythink.rewardvideo.api.ATRewardVideoAd;
import com.anythink.rewardvideo.api.ATRewardVideoListener;
import com.google.gson.Gson;
import com.work.game.ad.inter.RewardAdCallbackInter;
import com.work.game.config.UrlAddressConfig;
import com.work.game.config.UrlConfig;
import com.work.game.home.ui.model.vo.AdRecordVo;
import com.work.game.home.ui.model.vo.UserDailyActivityVo;
import com.work.game.utils.risk.DeviceUtils;
import com.work.game.utils.risk.RiskUtils;
import com.work.game.utils.risk.VirtualApkCheckUtil;
import com.work.game.volley.BaseFragment;
import com.android.volley.Request;
import com.work.game.volley.state.HUCState;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 激励视频
 */
public class TaKuRewardAdCallback implements ATRewardVideoListener {
    private static String TAG = "TaKuRewardAdCallback";

    private ATRewardVideoAd mRewardVideoAd;

    private String userId;
    private String token;
    private String returnOrderId;
    private String orderId;
    private BaseFragment baseFragment;
    private AlertDialog alertDialog;
    private RewardAdCallbackInter rewardAdCallbackInter;
    private Activity activity;
    private String placementId;
    private static volatile TaKuRewardAdCallback instance;

    private boolean flag = false;

    private TaKuRewardAdCallback() {
    }

    public static synchronized TaKuRewardAdCallback getInstance() {
        if (ObjectUtil.isNull(instance)) {
            synchronized (TaKuRewardAdCallback.class) {
                if (ObjectUtil.isNull(instance)) {
                    instance = new TaKuRewardAdCallback();
                }
            }
        }
        return instance;
    }

    public void loadAd(Context context, String placementId) {
        this.placementId = placementId;
        mRewardVideoAd = new ATRewardVideoAd(context, placementId);
        randomOrderId();
        if (ObjectUtil.isNotNull(activity)) {
            mRewardVideoAd.setAdListener(this);
        }
        mRewardVideoAd.load();
    }

    public void showAd(Activity activity) {
        this.activity = activity;
        if (ObjectUtil.isNull(mRewardVideoAd)) {
            flag = true;
            loadAd(activity.getApplicationContext(), placementId);
            return;
        }
        if (mRewardVideoAd.isAdReady()) {
            alertDialog.dismiss();
            mRewardVideoAd.setAdListener(this);
            mRewardVideoAd.show(activity, getATShowConfig());
        } else {
            //重新加载
            randomOrderId();
            mRewardVideoAd.setAdListener(this);
            flag = true;
            mRewardVideoAd.load();
        }
    }

    @Override
    public void onRewardedVideoAdLoaded() {
        if (ObjectUtil.isNotNull(activity) && flag) {
            alertDialog.dismiss();
            mRewardVideoAd.show(activity, getATShowConfig());
            flag = false;
        }
    }

    @Override
    public void onRewardedVideoAdFailed(AdError adError) {
        Log.e(TAG, "onRewardedVideoAdFailed:" + adError.getFullErrorInfo());
        if (ObjectUtil.isNotNull(activity) && flag) {
            alertDialog.dismiss();
            Toast.makeText(baseFragment.getActivity(), "视频加载失败", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onRewardedVideoAdPlayStart(ATAdInfo atAdInfo) {
        Log.e(TAG, "onRewardedVideoAdFailed:" + atAdInfo.getAdNetworkType());
        if (ObjectUtil.isNotNull(atAdInfo)) {
            Double ecpm = atAdInfo.getPublisherRevenue(); //展示广告的价格 0.105234661721
            ecpm = ecpm * 100000;
            int firmId = atAdInfo.getNetworkFirmId();  //展示广告的adn名称
            String sdkName = "other";
            switch (firmId) {
                case 28://快手
                    sdkName = "ks";
                    break;
                case 8://腾讯广告(优量汇)
                    sdkName = "gdt";
                    break;
                case 15://穿山甲（CSJ）
                    sdkName = "pangle";
                    break;
                default: //其他
                    break;
            }
            String slotId = atAdInfo.getNetworkPlacementId(); //展示广告的代码位ID
            AdRecordVo adRecordVo = new AdRecordVo();
            adRecordVo.setArTransId(orderId);
            adRecordVo.setEcpm(String.valueOf(ecpm.intValue()));
            adRecordVo.setToken(token);
            adRecordVo.setArChannel(sdkName);
            adRecordVo.setArMediationRit(slotId);
            //采集数据
            //是否分身
            boolean flag = VirtualApkCheckUtil.getSingleInstance().checkByCreateLocalServerSocket(DeviceUtils.getInstance().getPackageName(Objects.requireNonNull(baseFragment.getActivity())));
            adRecordVo.setUdaSeparation(String.valueOf(flag ? 1 : 2));
            //是否模拟器
            flag = RiskUtils.getInstance().detectEmulator(baseFragment.getActivity());
            adRecordVo.setUdaSimulator(String.valueOf(flag ? 1 : 2));
            //是否开启调试模式
            flag = DeviceUtils.getInstance().isDeveloperModeEnabled(baseFragment.getActivity());
            adRecordVo.setUdaDebugMode(String.valueOf(flag ? 1 : 2));
            //是否USB调试模式
            flag = DeviceUtils.getInstance().isAdbEnabled(baseFragment.getActivity());
            adRecordVo.setUdaUsbMode(String.valueOf(flag ? 1 : 2));
            //是否root
            flag = DeviceUtils.getInstance().isDeviceRooted(baseFragment.getActivity());
            adRecordVo.setUdaRoot(String.valueOf(flag ? 1 : 2));
            //是否开启无障碍模式
            flag = DeviceUtils.getInstance().isAccessibilityServiceEnabled(baseFragment.getActivity());
            adRecordVo.setUdaAccessibility(String.valueOf(flag ? 1 : 2));
            //是否开启VPN代理模式
            flag = DeviceUtils.getInstance().isWifiProxy();
            adRecordVo.setUdaVpnProxy(String.valueOf(flag ? 1 : 2));

            //手机应用总数
            List<PackageInfo> packageInfoList = DeviceUtils.getInstance().getAllApps(baseFragment.getActivity());
            adRecordVo.setUdaAllApp(String.valueOf(ObjectUtil.isNotEmpty(packageInfoList) ? packageInfoList.size() : 0));
            List<UserDailyActivityVo> userDailyActivityVoList = new ArrayList<>();
            for (PackageInfo packageInfo : packageInfoList) {
                UserDailyActivityVo userDailyActivityVo = new UserDailyActivityVo();
                String name = DeviceUtils.getInstance().getAppName(baseFragment.getActivity(), packageInfo.packageName);
                userDailyActivityVo.setUdaPackage(packageInfo.packageName);
                userDailyActivityVo.setUdaAppName(name);
                userDailyActivityVo.setUdaVersionCode(packageInfo.versionName);
                userDailyActivityVoList.add(userDailyActivityVo);
            }
            Gson gson = new Gson();
            // 将 User 对象转换为 JSON 字符串
            String jsonString = gson.toJson(userDailyActivityVoList);
            //应用JSON明细
            adRecordVo.setUdaAllAppDetail(jsonString);
            baseFragment.hucRequestInterfase.executeStr(baseFragment, null, HUCState.HUC_REQEUST_CODE_5, Request.Method.POST, UrlConfig.URL_AD_RECORD, baseFragment.hucParameInterfase.getRequestParameter(adRecordVo), true);
        }
        //建议在此回调中调用load进行广告的加载，方便下一次广告的展示（不需要调用isAdReady()）
        returnOrderId = orderId;
        randomOrderId();
        mRewardVideoAd.load();
    }

    @Override
    public void onRewardedVideoAdPlayEnd(ATAdInfo atAdInfo) {
    }

    @Override
    public void onRewardedVideoAdPlayFailed(AdError adError, ATAdInfo atAdInfo) {
    }

    @Override
    public void onRewardedVideoAdClosed(ATAdInfo atAdInfo) {
        rewardAdCallbackInter.rewardAdCallback(returnOrderId);
    }

    @Override
    public void onRewardedVideoAdPlayClicked(ATAdInfo atAdInfo) {
        Log.e(TAG, "onRewardedVideoAdPlayClicked:" + atAdInfo.getAdNetworkType());
    }

    @Override
    public void onReward(ATAdInfo atAdInfo) {
        Log.e(TAG, "onReward:" + atAdInfo.getAdNetworkType());
    }

    private void randomOrderId() {
        orderId = UUID.randomUUID().toString().replace("-", "");
        Map<String, Object> localMap = new HashMap<>();
        localMap.put(ATAdConst.KEY.USER_ID, userId);
        localMap.put(ATAdConst.KEY.USER_CUSTOM_DATA, orderId);
        mRewardVideoAd.setLocalExtra(localMap);
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public void setBaseFragment(BaseFragment baseFragment) {
        this.baseFragment = baseFragment;
    }

    public void setRewardAdCallbackInter(RewardAdCallbackInter rewardAdCallbackInter) {
        this.rewardAdCallbackInter = rewardAdCallbackInter;
    }

    public void setAlertDialog(AlertDialog alertDialog) {
        this.alertDialog = alertDialog;
    }

    private ATShowConfig getATShowConfig() {
        orderId = UUID.randomUUID().toString().replace("-", "");
        ATShowConfig.Builder builder = new ATShowConfig.Builder();
        builder.scenarioId(userId);
        builder.showCustomExt(orderId + StrUtil.COMMA + UrlAddressConfig.CHANNEL_PACKAGE);
        return builder.build();
    }
}
